package com.lcy.reggie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcy.reggie.common.Result;
import com.lcy.reggie.dto.UserDto;
import com.lcy.reggie.entity.User;
import com.lcy.reggie.service.UserService;
import com.lcy.reggie.mapper.UserMapper;
import com.lcy.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * @author ChunBaBa_
 * @description 针对表【user(用户信息)】的数据库操作Service实现
 * @createDate 2023-01-17 16:11:41
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public Result<String> sendMsg(User user, HttpSession session) {

        String email = user.getEmail();
        if (StringUtils.isNotBlank(email)) {

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject("验证码邮件");//主题
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.err.println("验证码："+code);

            //将随机数放置到session中
            session.setAttribute("email", email);
            session.setAttribute("code", code);

            mailMessage.setText("你收到的验证码是：" + code); //内容

            mailMessage.setTo(email);

            mailMessage.setFrom(from);

            mailSender.send(mailMessage); //发送

            return Result.success("验证码发送成功！");
        }

        return Result.error("短信发送失败");
    }

    /**
     *  登录验证
     * @param userDto
     * @param session
     * @return
     */
    @Override
    public Result<User> login(UserDto userDto, HttpSession session) {
        String code = (String) session.getAttribute("code");
        String email = (String) session.getAttribute("email");

        if(code.equals(userDto.getCode())){
            // 先判断数据库中是否有该邮箱，如果是第一次登录，就保存在邮箱
            User user = this.query().eq("email", userDto.getEmail()).one();
            if(user == null){
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                save(user);
            }
            session.setAttribute("user",user.getId());
            return Result.success(user);
        }
        return Result.error("登陆失败！");
    }
}




